package com.timmy.chi.ui.activity;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.google.gson.Gson;
import com.timmy.chi.MyApp;
import com.timmy.chi.R;
import com.timmy.chi.choosephoto.CropImageActivity;
import com.timmy.chi.choosephoto.DealPictureUtils;
import com.timmy.chi.choosephoto.ImageChooseActivity_new;
import com.timmy.chi.choosephoto.IntentConstants;
import com.timmy.chi.model.beans.AddFood;
import com.timmy.chi.model.beans.ImageUpLoad;
import com.timmy.chi.utils.CloseUtils;
import com.timmy.chi.utils.Constants;
import com.timmy.chi.utils.network.MyHttp;
import com.timmy.chi.utils.network.ResultCallback;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 添加菜品
 */

public class AddFoodActivity extends AppCompatActivity {

    private static final String TAG = "AddFoodActivity";
    @BindView(R.id.et_foodname)
    EditText mEtFoodname;
    @BindView(R.id.et_foodme)
    EditText mEtFoodme;
    @BindView(R.id.et_foodprice)
    EditText mEtFoodprice;
    @BindView(R.id.et_cooktime)
    EditText mEtFoodCookTime;
    @BindView(R.id.radioGroup)
    RadioGroup mRadioGroup;
    @BindView(R.id.iv_food)
    ImageView mIvFood;
    private Gson mGson;
    private String mKey;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_addfood);
        ButterKnife.bind(this);
        mGson = new Gson();
    }

    @OnClick({R.id.iv_back, R.id.addfood, R.id.iv_food})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                Intent intent = new Intent(this, AdminActivity.class);
                startActivity(intent);
                finish();
                break;
            case R.id.addfood:
                addFood();
                break;
            case R.id.iv_food:


                Dialog dialog = new AlertDialog.Builder(this).setTitle(null).setMessage("选择图片方式？")
                        .setNegativeButton("拍照", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                dialogInterface.dismiss();

                                Intent intentFromCapture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                                String state = Environment.getExternalStorageState();
                                if (state.equals(Environment.MEDIA_MOUNTED)) {
                                    File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
                                    File file = new File(path, "food.jpg");
                                    intentFromCapture.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
                                }
                                startActivityForResult(intentFromCapture, CAMERA);

                            }
                        })
                        .setPositiveButton("选择图片", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Intent intent2 = new Intent(AddFoodActivity.this, ImageChooseActivity_new.class);
                                startActivityForResult(intent2, 2);
                            }
                        }).show();
                break;
        }
    }

    private void addFood() {
        String foodName = mEtFoodname.getText().toString().trim();
        String foodMet = mEtFoodme.getText().toString().trim();
        String foodPri = mEtFoodprice.getText().toString().trim();
        String cookTime = mEtFoodCookTime.getText().toString().trim();
        int cookingTime = Integer.parseInt(cookTime);


        double price;
        try {
            price = Double.parseDouble(foodPri);
        } catch (NumberFormatException e) {
            showToast("价格输入错误");
            e.printStackTrace();
            return;
        }

        if (TextUtils.isEmpty(foodName)) {
            showToast("菜品名不能为空");
            return;
        }

        final int id = getRadioGroupId();

        if (mKey == null) {

            mKey = "";
            switch (id) {
                case 1:
                    mKey = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1493639771989&di=e56124c3d5fd2a73980cb7316d61898a&imgtype=0&src=http%3A%2F%2Fpic.syd.com.cn%2F0%2F101%2F06%2F88%2F101068813_00000000a96b96fb.jpg";
                    break;
                case 2:
                    mKey = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1493639864873&di=f50c1ba84f2b7ebd391336414fc78068&imgtype=0&src=http%3A%2F%2Fpic2.ooopic.com%2F13%2F48%2F31%2F25bOOOPIC01_1024.jpg";
                    break;
                case 3:
                    mKey = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1493639882795&di=f6c6567220c3f46cda2850e8f044ab1d&imgtype=0&src=http%3A%2F%2Fpic.58pic.com%2F58pic%2F13%2F91%2F97%2F45z58PICAn5_1024.jpg";
                    break;
                case 4:
                    mKey = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1493639893565&di=e6976411ec0cd289a534c5fd490ef517&imgtype=0&src=http%3A%2F%2Fpic18.nipic.com%2F20120201%2F6608733_103735772000_2.jpg";
                    break;
            }
        }

        MyHttp.addFood(foodName, price, foodMet, mKey, cookingTime, id, new ResultCallback() {
            @Override
            public void onSuccess(String s) {
                AddFood addFood = mGson.fromJson(s, AddFood.class);
                if (addFood.getResponseState() == 0) {
                    showToast("添加成功");
                } else {
                    showToast("添加失败");
                }
            }

            @Override
            public void onError() {
                showToast("请检查网络");
            }
        });

    }

    private void showToast(String message) {
        Toast.makeText(AddFoodActivity.this, message, Toast.LENGTH_SHORT).show();
    }

    public int getRadioGroupId() {

        int checkId = mRadioGroup.getCheckedRadioButtonId();

        switch (checkId) {
            case R.id.rb_liang:
                return 1;
            case R.id.rb_red:
                return 2;
            case R.id.rb_drink:
                return 3;
            case R.id.rb_dianxin:
                return 4;
        }
        return 0;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != -1) {
            return;
        }

        if (requestCode == PICTURE) {
            // 图片选择
            String pictureURI = data.getStringExtra(IntentConstants.PICTUREURI);
            File srcFile = new File(pictureURI);
            File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
            File targetFile = new File(path, "food.jpg");
            if (targetFile.exists()) {
                targetFile.delete();
            }
            File file = DealPictureUtils.copyFile(srcFile, targetFile);

            if (file != null) {
                CropImageActivity.jump2CropImageActivity(this, file.getPath(), CROPIMAGE);
            } else {
            }

        } else if (requestCode == CAMERA) {
            // 相机

            String state = Environment.getExternalStorageState();
            if (state.equals(Environment.MEDIA_MOUNTED)) {
                File cameraPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
                File tempFile = new File(cameraPath, "food.jpg");
                CropImageActivity.jump2CropImageActivity(this, tempFile.getPath(), CROPIMAGE);
            }

        } else if (requestCode == CROPIMAGE) {

            uploadHeadImag();
        }
    }

    private int PICTURE = 2;
    private int CAMERA = 3;
    private int CROPIMAGE = 4;

    private void uploadHeadImag() {
        final File file = new File(IMAGE_FILECACHE_PATH);
        file.mkdirs();
        if (file.exists()) {
            file.delete();
        }
        Bitmap photoBitmap = MyApp.getInstance().selectBitmap;

        compressBmpToFile(photoBitmap, file);
        // HttpUtil.uploadHeadImage(file);

        mIvFood.setImageBitmap(BitmapFactory.decodeFile(file.getAbsolutePath()));

        //        MyHttp.upLoadingImg(file);
        new Thread(new Runnable() {
            @Override
            public void run() {
                uploadFile(file);
            }
        }).start();
    }

    private void uploadFile(File file) {
        try {
            URL url = new URL("http://120.25.226.120:8080/resource/uploadImage");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setConnectTimeout(15000);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            //            int resCode = conn.getResponseCode();
            //            if(resCode > 299 || resCode < 200){
            //                Log.i(TAG, "uploadFile: resCode = " + resCode);
            //            }

            OutputStream os = conn.getOutputStream();
            FileInputStream fis = new FileInputStream(file);
            writeStream(fis, os);

            os.close();
            fis.close();
            InputStream is = conn.getInputStream();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            writeStream(is, baos);
            ImageUpLoad upLoad = mGson.fromJson(baos.toString(), ImageUpLoad.class);

            if (upLoad.getResponseState() == 0) {
                mKey = "http://120.25.226.120:8080/resource/image?key=" + upLoad.getKey();
            }

            baos.close();
            is.close();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    private void writeStream(InputStream is, OutputStream os) throws IOException {
        int len;
        byte[] b = new byte[1024];

        while ((len = is.read(b)) > 0) {
            os.write(b, 0, len);
        }
    }


    private static final String IMAGE_FILECACHE_PATH = Constants.SDCARDPATH + "MyImgcache.jpg";


    public void compressBmpToFile(Bitmap bmp, File file) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int options = 80;
        bmp.compress(Bitmap.CompressFormat.JPEG, options, baos);
        while (baos.toByteArray().length / 1024 > 300) {
            baos.reset();
            options -= 10;
            bmp.compress(Bitmap.CompressFormat.JPEG, options, baos);
        }

        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
            fos.write(baos.toByteArray());
            fos.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            CloseUtils.closeQuiety(fos);
        }
    }
}
